<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="45%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <el-form-item label="用户账号" prop="account">
          <el-input v-model="formData.account" placeholder="请输入用户账号" />
        </el-form-item>
        <el-form-item label="用户密码" prop="pwd">
          <el-input v-model="formData.pwd" placeholder="请输入用户密码" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="formData.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker clearable v-model="formData.birthday" type="date" value-format="timestamp" placeholder="选择生日" />
        </el-form-item>
        <el-form-item label="身份证号码" prop="cardId">
          <el-input v-model="formData.cardId" placeholder="请输入身份证号码" />
        </el-form-item>
        <el-form-item label="用户分组" prop="groupId">
          <el-select v-model="formData.groupId" placeholder="请选择用户分组">
            <el-option
              v-for="item in groupOptions"
              :key="item.id"
              :label="item.groupName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="tagName">
          <el-select v-model="formData.tagId" placeholder="请选择标签">
            <el-option
              v-for="item in tagOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="用户头像">
          <ImageUpload v-model="formData.avatar"/>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="用户余额" prop="nowMoney">
          <el-input v-model="formData.nowMoney" placeholder="请输入用户余额" />
        </el-form-item>
        <el-form-item label="用户剩余积分" prop="integral">
          <el-input v-model="formData.integral" placeholder="请输入用户剩余积分" />
        </el-form-item>
        <el-form-item label="详细地址" prop="addres">
          <el-input v-model="formData.addres" placeholder="请输入详细地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as sApi from '@/api/user/users';
import ImageUpload from '@/components/ImageUpload';
import * as groupApi from '@/api/user/usergroup'
import * as tagApi from '@/api/user/usertag'

export default {
  name: "sForm",
  components: {
    ImageUpload,
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 用户分组选项
      groupOptions: [],
      // 用户标签选项
      tagOptions: [],
      // 表单参数
      formData: {
        uid: undefined,
        account: undefined,
        pwd: undefined,
        realName: undefined,
        birthday: undefined,
        cardId: undefined,
        groupId: undefined,
        tagId: undefined,
        nickname: undefined,
        avatar: undefined,
        phone: undefined,
        nowMoney: undefined,
        integral: undefined,
        addres: undefined,
      },
      // 表单校验
      formRules: {
        account: [{ required: true, message: '用户账号不能为空', trigger: 'blur' }],
      },
    };
  },
  created() {
    // 获取用户分组数据
    this.getGroupOptions();
    // 获取用户标签数据
    this.getTagOptions();
  },
  methods: {
    /** 获取用户分组选项 */
    async getGroupOptions() {
      try {
        const res = await groupApi.getGroupPage({
          pageNo: 1,
          pageSize: 100  // 使用允许的最大值
        });
        console.log('用户分组数据:', res.data.list);
        this.groupOptions = res.data.list || [];
      } catch (error) {
        console.error('获取用户分组失败:', error);
        this.$modal.msgError('获取用户分组失败');
      }
    },
    /** 获取用户标签选项 */
    async getTagOptions() {
      try {
        const res = await tagApi.getTagPage({
          pageNo: 1,
          pageSize: 100  // 使用允许的最大值
        });
        console.log('用户标签数据:', res.data.list);
        this.tagOptions = res.data.list || [];
      } catch (error) {
        console.error('获取用户标签失败:', error);
        this.$modal.msgError('获取用户标签失败');
      }
    },
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await sApi.gets(id);
          this.formData = res.data;
          this.title = "修改用户";
        } finally {
          this.formLoading = false;
        }
      }
      this.title = "新增用户";
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = { ...this.formData };
        if (Array.isArray(data.avatar)) {
          data.avatar = data.avatar[0] || '';
        }
        // 修改的提交
        if (data.uid) {
          await sApi.updates(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await sApi.creates(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        uid: undefined,
        account: undefined,
        pwd: undefined,
        realName: undefined,
        birthday: undefined,
        cardId: undefined,
        groupId: undefined,
        tagId: undefined,
        nickname: undefined,
        avatar: undefined,
        phone: undefined,
        nowMoney: undefined,
        integral: undefined,
        addres: undefined,
      };
      this.resetForm("formRef");
    }
  }
};
</script>
